<template>
  <el-row :gutter="10" style="height: 100%">
    <el-col :span="1">
      <div style="width: 5px;height: 100%;background-color: #22ccee;float: right"></div>
    </el-col>
    <el-col :span="23">
      <p style="font-weight: bold;float: left" v-if="uId!=null||(id==null&&Id==null)">新建预约</p>
      <p style="font-weight: bold;float: left" v-if="Id!=null">更新预约</p>
      <p style="font-weight: bold;float: left" v-if="id!=null">查看预约</p>
    </el-col>
  </el-row>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-form-item label="预约号:" label-width="410">
        <el-input v-model="appointment.appointment" placeholder="根据规则自动生成"
                  class="formInput" disabled/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="姓名:" label-width="110" :required="true">
        <el-select v-if="uId==null" v-model="appointment.patientId" class="formInput"
                   placeholder="请选择" @change="changeUser(appointment.patientId)"
                   :disabled="id!=null||Id!=null">
          <el-option v-for="p in patients" :label="p.nickname" :value="p.id"/>
        </el-select>
        <el-select v-else v-model="patient.nickname" class="formInput"
                   :disabled="true"/>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-form-item label="预约项目:" label-width="410" :required="true">
        <el-select v-model="appointment.project" placeholder="请选择"
                   class="formInput" :disabled="id!=null">
          <el-option v-for="item in c1" :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="预约类型:" label-width="110" :required="true">
        <el-select v-model="appointment.type" placeholder="请选择"
                   class="formInput" :disabled="id!=null">
          <el-option v-for="item in c2" :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-form-item label="性别:" label-width="410">
        <el-input v-model="patient.gender" class="formInput" disabled/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="手机号码:" label-width="110">
        <el-input v-model="patient.mobile" class="formInput" disabled/>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-form-item label="科室:" label-width="410" :required="true">
        <el-select v-model="appointment.departmentId" class="formInput"
                   placeholder="请选择" @change="changeDepartment(appointment.departmentId)"
                   :disabled="id!=null">
          <el-option v-for="d in department" :key="d.id" :label="d.name" :value="d.id"/>
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="就诊卡号:" label-width="110">
        <el-input v-model="patient.number" class="formInput" disabled/>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-form-item label="预约医生 :" label-width="410" :required="true">
        <el-select v-model="appointment.doctorId" placeholder="请选择"
                   class="formInput" :disabled="id!=null">
          <el-option v-for="d in doctor" :key="d.id" :label="d.nickname" :value="d.id"/>
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="预约时间 :" label-width="110" :required="true">
        <el-date-picker v-model="appointment.createDate" type="date"
                        placeholder="请选择" format="YYYY-MM-DD"
                        :disabled="id!=null"/>
        <span>&nbsp; - &nbsp;</span>
        <el-time-select v-model="appointment.createTime" placeholder="请选择"
                        start="08:00" step="00:30" end="18:00"
                        :disabled="id!=null"/>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row>
    <el-form-item label="备注:" label-width="410">
      <el-input v-model="appointment.remark" type="textarea" :rows="10"
                style="width: 810px;" :disabled="id!=null"/>
    </el-form-item>
  </el-row>
  <div v-if="id==null">
    <el-row :gutter="10" style="margin-top: 20px">

      <el-col :span="12" style="padding-right: 100px">
        <el-button style="float: right;background-color: #409EFF;color: white;width: 80px"
                   @click="save">提交
        </el-button>
      </el-col>
      <el-col :span="12" style="padding-left: 100px">
        <el-button style="float: left;color: #409EFF;border: 1px solid #409EFF;width: 80px"
                   @click="back">返回
        </el-button>
      </el-col>
    </el-row>
  </div>
  <div v-else>
    <el-button style="color: #409EFF;border: 1px solid #409EFF;width: 160px"
               @click="back">返 &nbsp; &nbsp; &nbsp; 回
    </el-button>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import router from '@/router';
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

const appointment = ref({});
const patients = ref([]);
const patient = ref({});
const doctor = ref([]);
const department = ref([]);

const c1 = [{value: '入职体检'}, {value: '普通体检'}, {value: '就诊挂号'}, {value: '其他'},]
const c2 = [{value: '普通号'}, {value: '专家号'}, {value: '名医号'}]

let id = new URLSearchParams(location.search).get('id');
let Id = new URLSearchParams(location.search).get('Id');
let uId = new URLSearchParams(location.search).get('uId');

const userToken = ref(localStorage.getItem('user-token') ?
    JSON.parse(localStorage.getItem('user-token')) : null);

onMounted(() => {
  if (userToken.value == null) {
    ElMessage.error("请先登录!");
    router.push('/patient/login');
    return;
  }
  axios.defaults.headers.common['Authorization'] = userToken.value;
  if (uId != null) {
    axios.get(BASE_URL + "/v1/patients/" + uId + "/select").then((response) => {
      if (response.data.code === 20000) {
        patient.value = response.data.data;
        appointment.value.patientId = uId;
      }
    })
  }
  if (Id != null) {
    selectById(Id);
  }
  if (id != null) {
    selectById(id);
  }
  axios.get(BASE_URL + "/v1/users/select").then((response) => {
    if (response.data.code === 20000) {
      patients.value = response.data.data;
    }
  })
  axios.get(BASE_URL + "/v1/doctors/type").then((response) => {
    if (response.data.code === 20000) {
      doctor.value = response.data.data;
    }
  })
  axios.get(BASE_URL + "/v1/department/select-level").then((response) => {
    if (response.data.code === 20000) {
      department.value = response.data.data;
    }
  })
})

const selectById = (id) => {
  axios.get(BASE_URL + "/v1/appointments/" + id + "/select").then((response) => {
    if (response.data.code === 20000) {
      appointment.value = response.data.data;
      appointment.value.createTime = appointment.value.createDate.substring(11, 16);
      axios.get(BASE_URL + "/v1/patients/" + appointment.value.patientId + "/select").then((response) => {
        if (response.data.code === 20000) {
          patient.value = response.data.data;
        }
      })
    }
  })
}

const changeUser = (id) => {
  axios.get(BASE_URL + "/v1/users/select/" + id).then((response) => {
    if (response.data.code === 20000) {
      patient.value = response.data.data;
    }
  })
}

const changeDepartment = (id) => {
  axios.get(BASE_URL + "/v1/department/selectDoctor/" + id).then((response) => {
    if (response.data.code === 20000) {
      doctor.value = response.data.data;
      appointment.value.doctorId = '';
    }
  })
}

const save = () => {
  if (appointment.value.patientId == null) {
    ElMessage.error("请选择需要预约的患者!")
    return;
  }
  if (appointment.value.type == null) {
    ElMessage.error("请选择预约类型!")
    return;
  }
  if (appointment.value.project == null) {
    ElMessage.error("请选择预约的项目!")
    return;
  }
  if (appointment.value.departmentId == null) {
    ElMessage.error("请选择想要预约的科室!")
    return;
  }
  if (appointment.value.doctorId == null) {
    ElMessage.error("请选择想要预约的医生!")
    return;
  }
  if (appointment.value.createDate == null) {
    ElMessage.error("请选择想要预约的日期!")
    return;
  }
  if (appointment.value.createTime == null) {
    ElMessage.error("请选择想要预约的时间段!")
    return;
  }
  const date = new Date(appointment.value.createDate);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = appointment.value.createTime.substring(0, 2);
  const minutes = appointment.value.createTime.substring(3);
  appointment.value.createDate = `${year}-${month}-${day} ${hours}:${minutes}:00`;
  let data = qs.stringify(appointment.value);
  if (Id == null) {
    axios.post(BASE_URL + "/v1/appointments/insert", data).then((response) => {
      if (response.data.code === 20000) {
        ElMessage.success("新建预约成功!")
        router.push('/admin/appointment')
      } else {
        ElMessage.warning(response.data.message)
      }
    })
  } else {
    axios.post(BASE_URL + "/v1/appointments/update", data).then((response) => {
      if (response.data.code === 20000) {
        ElMessage.success("更新预约成功!")
        router.push('/admin/appointment')
      } else {
        ElMessage.warning(response.data.message)
      }
    })
  }
}

const back = () => {
  if (uId != null) {
    router.push('/admin/formPatient?id=' + uId);
  } else {
    router.push('/admin/appointment');
  }
}
</script>

<style scoped>
.el-select {
  width: 140px;
}

/deep/ .el-date-editor {
  --el-date-editor-width: 140px;
}

.formInput {
  width: 300px;
  height: 35px;
}
</style>